# 导入所需的库
import cv2, Leap, math, ctypes
import numpy as np
import time
import cPickle as pickle 

# 导入自定义支持函数
from supportFunctions import *

# 创建 Leap Motion 控制器对象
controller = Leap.Controller()
# 允许访问原始图像数据
controller.set_policy(Leap.Controller.POLICY_IMAGES)

# 等待一段时间，确保 Leap Motion 控制器已准备好
time.sleep(0.1)

# 设置要捕获的图像数量
numImages = 100
rawImages = []
images = []

# 记录开始时间
startTime = time.time()

# 循环捕获图像
for i in range(numImages):
    # 获取 Leap Motion 控制器的当前帧
    frame = controller.frame()
    # 获取左摄像头的图像
    image = frame.images[0]

    # 将图像数据封装成 NumPy 数组
    i_address = int(image.data_pointer)
    ctype_array_def = ctypes.c_ubyte * image.height * image.width
    # 转换为 ctypes 数组
    as_ctype_array = ctype_array_def.from_address(i_address)
    # 转换为 NumPy 数组
    as_numpy_array = np.ctypeslib.as_array(as_ctype_array)
    rawImage = np.reshape(as_numpy_array, (image.height, image.width))

    # 获取图像的畸变矫正参数
    left_coordinates, left_coefficients = convert_distortion_maps(frame.images[0])

    # 将原始图像和畸变矫正参数存储起来
    rawImages.append((left_coordinates, left_coefficients, rawImage))

# 记录图像捕获完成所需的时间
elapsedTime = time.time() - startTime
print 'Done Capturing! ' + str(len(images)) + ' images captured in ' + str(elapsedTime) + ' seconds.'
print 'Effective Frame Rate = ' + str(float(len(images))/elapsedTime) + ' images/second.'
print 'Processing Images...'

#print '捕获完成！共捕获 ' + str(len(images)) + ' 张图像，用时 ' + str(elapsedTime) + ' 秒。'
#print '有效帧率 = ' + str(float(len(images)) / elapsedTime) + ' 张图像/秒。'
#print '处理图像...'

# 遍历处理原始图像
for i in range(len(rawImages)):
    # 获取畸变矫正参数和原始图像
    (left_coordinates, left_coefficients, rawImage) = rawImages[i]
    # 使用 OpenCV 中的 remap 函数进行畸变矫正
    destination = cv2.remap(rawImage, left_coordinates, left_coefficients, interpolation=cv2.INTER_LINEAR)
    # 调整图像大小
    destination = cv2.resize(destination, (400, 400), 0, 0, cv2.INTER_LINEAR)
    # 存储处理后的图像
    images.append(destination)

# 定义 pickle 文件名
pickleName = 'video'
pickleFileName = pickleName + ".pickle"
# 打开 pickle 文件并将处理后的图像列表保存到文件中
pickleFile = open(pickleFileName, 'wb')
pickle.dump(images, pickleFile, pickle.HIGHEST_PROTOCOL)
pickleFile.close()

# 记录整个过程所需的时间
elapsedTime = time.time() - startTime
print 'Done!' + ' Total time = ' + str(elapsedTime) + ' s.'